import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {GnHttpInterceptorConfig} from './HttpInterceptorConfig';
import {GnOAuthUtils} from './OAuthUtils';
import {GnSiteInfo} from './SiteInfo';
import {Router} from '@angular/router';

@Injectable()
export class GnOAuthHttpInterceptor implements HttpInterceptor {

  private oAuthUtils = new GnOAuthUtils();

  constructor(private config: GnHttpInterceptorConfig,
              private siteInfo: GnSiteInfo,
              private route: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let headers = req.headers;
    if (this.config.startWithUrl
      && req.url.startsWith(this.config.startWithUrl)
      && !this.config.ignoreUrls.includes(req.url)) {
      const token = this.oAuthUtils.getToken();
      if (this.oAuthUtils.tokenExpired(token)) {
        if (this.siteInfo && this.siteInfo.loginUrl) {
          this.route.navigateByUrl(this.siteInfo.loginUrl);
        }
      } else {
        headers = req.headers.set('Authorization', 'Bearer ' + token);
      }
    }
    return next.handle(req.clone({
      headers
    }));
  }

}
